<template>
    <div
      class="page w-full h-full flex flex-col"
      @touchstart="touchStart"
      @touchend="touchEnd"
      :style="{backgroundColor:bgColor}"
    >
      <NavBar :title="title" v-if="title" :on-back="onPageBack">
        <template #custom>
          <slot name="navBarCustom"></slot>
        </template>
      </NavBar>
      <div class="flex-1 over">
        <slot name="content"></slot>
      </div>
    </div>
  </template>
  
  <script>
  import NavBar from '@/components/nav-bar/newNavBar'
  
  export default {
    components: {
      NavBar
    },
    props: {
      title: {
        type: String,
        default: ''
      },
      onPageBack: {
        type: [Function, undefined],
        default: undefined
      },
      bgColor:{
        type:String,
        default:"#fff"
      }
    },
    data() {
      return {
        // 刚触碰的时间
        startTime: 0,
        // 刚触碰的位置
        startPositionX: 0,
        startPositionY: 0,
        // 结束的位置
        endPositionX: 0,
        endPositionY: 0
      }
    },
    methods: {
      touchStart(event) {
        // 获取初始时间
        this.startTime = Date.now()
        // 获取初始的位置
        this.startPositionX = event.changedTouches[0].clientX
        this.startPositionY = event.changedTouches[0].clientY
      },
      touchEnd(event) {
        const endTime = Date.now()
        if (endTime - this.startTime > 2000) {
          // 如果手指滑动的距离超过2s 就默认不合法
          return
        }
  
        this.endPositionX = event.changedTouches[0].clientX
        this.endPositionY = event.changedTouches[0].clientY
        const xGap = Math.abs(this.endPositionX - this.startPositionX)
        const yGap = Math.abs(this.endPositionY - this.startPositionY)
        // 判断其滑动的距离是否值得触发
        let direction = ''
        if (xGap > yGap && xGap > 100) {
          direction = this.endPositionX - this.startPositionX > 0 ? 'right' : 'left'
        } else if (yGap > xGap && yGap > 100) {
          direction = this.endPositionY - this.startPositionY > 0 ? 'down' : 'up'
        } else {
          return
        }
        this.$emit('gesture', direction)
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .page {
    width: 100%;
    height: 100vh;
  
    .over {
      overflow-x: hidden;
    }
  }
  </style>
  